package org.example.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.DynamicTableNameInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.example.entity.SysUserEntity;
import org.example.utils.SecurityUtils;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * mybatis-plus配置
 *
 * @author Mark sunlightcs@gmail.com
 * @since 2.0.0 2018-02-05
 */
@Slf4j
@Configuration
@MapperScan(basePackages = {"org.example.dao"})
public class MybatisPlusConfig {


    /**
     * 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 动态修模式名
        DynamicTableNameInnerInterceptor dynamicTableNameInnerInterceptor = new DynamicTableNameInnerInterceptor();
        dynamicTableNameInnerInterceptor.setProperties(null);
        dynamicTableNameInnerInterceptor.setTableNameHandler((sql, tableName) -> {
            String schema = "";
            if ("t_user".contains(tableName)) {
                log.info("=============租户模式相关表==={}", tableName);
                SysUserEntity sysUser = SecurityUtils.getUser();
                if (sysUser != null) {
                    schema = !"zuhu".equals(sysUser.getSelectTenantMode()) ? "" : sysUser.getSelectTenantMode();
                }
            }
            schema = "weblog" + (StringUtils.isBlank(schema) ? "" : ("_" + schema));
            return StringUtils.isBlank(schema) ? tableName : String.join(".", schema, tableName);

        });
        interceptor.addInnerInterceptor(dynamicTableNameInnerInterceptor);
        //向Mybatis过滤器链中添加分页拦截器
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        //还可以添加i他的拦截器
        return interceptor;
    }

    public static void main(String[] args) {
        System.out.println(String.join(".", null, "table"));
    }
}